﻿using System;
using System.Collections.Generic;
using System.Linq;///what hello
using System.Text; // I'm not a fan
using System.Data.SqlClient; // why not?
using System.Windows.Forms; // Skype is faster, and almost as useful
using System.Text.RegularExpressions; // what??? // I dunno. I don't have anything to show ATM. -- Unless you know the conversion of g/s -> S.I. (m/s/s/s?) Not sure :(

namespace GE_Database_Manager
{
	public class Standardized_Wrapper
	{
		public SqlConnection _connection;
        private String _databaseName;
        private String _currentDB;
        private ErrorLog _errorLog;

		/// <summary>
		/// Instantiate a new wrapper; creates a new Database if it doesn't exist already
		/// </summary>
		/// <param name="connection"></param>
		/// <param name="create"></param>
		/// <param name="databaseName"></param>
        public Standardized_Wrapper(SqlConnection connection, bool create, String databaseName)
        {
            this._connection = connection;
			_connection.Close();
            _databaseName = databaseName;


            // start the error log
            _errorLog = new ErrorLog();

            // check if the user wants to create a new database
            if (create)
                createDatabase();

        }

		private void OpenConnection()
		{
			_connection.Close();
			_connection.Open();
		}

        /// <summary>
        /// Sets the database on the proccess function of each database
        /// this will be use on the log, that way when now which database failed..
        /// </summary>
        public String CurrentDB
        {
            get
            {
                return _currentDB;
            }
            set 
            {
                _currentDB = value;
            } 
        
        }

		/// <summary>
		/// Creates a new database; prepopulates the [engr_units] and [data_source] tables
		/// </summary>
		/// <returns>True if creation completes successfully; False otherwise</returns>
		private bool createDatabase()
		{
			// Idea: One script, separated by GO option. Instead of using Server Management Objects, just split on GO and execute each one
			string[] sqlScripts = (Properties.Resources.ge_tables).Replace("GE_Standardized", _databaseName).Split(new string[] { "GO --Execute Batch" }, StringSplitOptions.RemoveEmptyEntries);

			try
			{
				SqlCommand sqlCmnd = new SqlCommand();
				sqlCmnd.CommandType = System.Data.CommandType.Text;
				sqlCmnd.Connection = _connection;

				sqlCmnd.Connection.Open();
				foreach (string sqlScript in sqlScripts)
				{
					sqlCmnd.CommandText = sqlScript;
					sqlCmnd.ExecuteNonQuery();
				}
				sqlCmnd.Connection.Close();
			}
            catch (SqlException sqlEx)
			{
				// TODO: handle
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return false;
			}

			return true;
		}


		#region Public Wrapper Functions
		/// <summary>
		/// Insert a machine
		/// </summary>
		/// <param name="serialNumber"></param>
		/// <param name="type"></param>
		/// <param name="site"></param>
		/// <param name="tag"></param>
		/// <param name="workOrder"></param>
		/// <param name="make"></param>
		/// <returns>The [machine_id] of the newly inserted machine; -1 if insertion failed</returns>
		public int InsertMachine(string serialNumber, string type, string site, string tag, string workOrder, string make)
		{
			// If Serial Number is blank
			if (serialNumber == "")
			{
				serialNumber = "UNKWN" + GetCountOfMachines();
			}

			// See if machine already exists
			int machineId = GetMachineIdBySerial(serialNumber);

			if (machineId != -1) return machineId;

			// Else try to insert machine
			try
			{
				OpenConnection();

				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.InsertMachine", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@Serial", serialNumber));
					cmd.Parameters.Add(new SqlParameter("@Type", type));
					cmd.Parameters.Add(new SqlParameter("@Site", site));
					cmd.Parameters.Add(new SqlParameter("@Tag", tag));
					cmd.Parameters.Add(new SqlParameter("@Workorder", workOrder));
					cmd.Parameters.Add(new SqlParameter("@Make", make));

					// execute the command
					int rowsAffected = cmd.ExecuteNonQuery();
					_connection.Close();

					// Return -1 if the machine was not inserted
                    if (rowsAffected == 0)
                    {
                        _errorLog.writeToLog(_currentDB, 
                            String.Format(@"Unable to insert machine 
                                => serialNumber:{0} type:{1} site{2} tag{3} workorder:{4} make{5}",
                                    serialNumber, type, site, tag,  workOrder, make));
                        return -1;
                    }
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				// Return -1 if the machine was not inserted
				//Console.WriteLine("Wrapper.cs\\InsertMachine: " + sqlEx.Message);
                // write to log
                _errorLog.writeToLog(_currentDB,sqlEx.Message);
				return -1;
			}

			// Get the ID of the newly inserted machine, or -1 if it failed
			return GetLatestMachineId();
		}

		/// <summary>
		/// Insert a Stage
		/// </summary>
		/// <param name="designation"></param>
		/// <param name="machineId"></param>
		/// <param name="fixedGear"></param>
		/// <param name="gearToothCount"></param>
		/// <param name="pinionToothCount"></param>
		/// <param name="sunToothCount"></param>
		/// <param name="planetToothCount"></param>
		/// <param name="ringToothCount"></param>
		/// <param name="planetCount"></param>
		/// <returns>[stage_id] of the new stage; -1 otherwise</returns>
		public int InsertStage(Designation designation, int machineId, Fixed? fixedGear, int? gearToothCount, int? pinionToothCount, int? sunToothCount, int? planetToothCount, int? ringToothCount, int? planetCount)
		{
			// See if stage already exists
			int stageId = GetStageIdByProperties(machineId, fixedGear, gearToothCount, pinionToothCount, sunToothCount, planetToothCount, ringToothCount, planetCount);

			if (stageId != -1) return stageId;

			// Else try to insert stage
			try
			{
				OpenConnection();

				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.InsertStage", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@Designation", (int)designation));
					cmd.Parameters.Add(new SqlParameter("@GearToothCount", gearToothCount));
					cmd.Parameters.Add(new SqlParameter("@PinionToothCount", pinionToothCount));
					cmd.Parameters.Add(new SqlParameter("@SunToothCount", sunToothCount));
					cmd.Parameters.Add(new SqlParameter("@PlanetToothCount", planetToothCount));
					cmd.Parameters.Add(new SqlParameter("@RingToothCount", ringToothCount));
					cmd.Parameters.Add(new SqlParameter("@PlanetCount", planetCount));
					if(fixedGear!=null)
						cmd.Parameters.Add(new SqlParameter("@Fixed", (int)fixedGear));
					cmd.Parameters.Add(new SqlParameter("@MachineId", machineId));

					// execute the command
					int rowsAffected = cmd.ExecuteNonQuery();
					_connection.Close();

					// Return -1 if the stage was not inserted
					if (rowsAffected != 1) 
                    {
                        _errorLog.writeToLog(_currentDB,
                            String.Format("Unable to insert Stage, machineid:{0}",machineId));
                        return -1;
                    }
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				// Return -1 if the stage was not inserted
				//Console.WriteLine("Standardized_Wrapper.cs\\InsertStage" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}

			// Get the ID of the newly inserted stage, or -1 if it failed
			return GetLatestStageId();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="pointName"></param>
		/// <param name="machineId"></param>
		/// <returns></returns>
		public int InsertSensor(string pointName, int stageId)
		{
			// See if stage already exists
			int sensorId = GetSensorIdByNameAndStage(pointName, stageId);

			if (sensorId != -1) return sensorId;

			// Else try to insert stage
			try
			{
				OpenConnection();

				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.InsertSensor", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@PointName", pointName));
					cmd.Parameters.Add(new SqlParameter("@StageId", stageId));

					// execute the command
					int rowsAffected = cmd.ExecuteNonQuery();
					_connection.Close();

					// Return -1 if the stage was not inserted
                    if (rowsAffected != 1)
                    {
                        _errorLog.writeToLog(_currentDB,
                            String.Format("Unable to insert Sensor, stageId:{0} pointName{1}",stageId,pointName));
                        return -1;
                    }
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				// Return -1 if the stage was not inserted
				//Console.WriteLine("Standardized_Wrapper.cs\\InsertSensor" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}

			// Get the ID of the newly inserted stage, or -1 if it failed
			return GetLastestSensorId();
		}

		/// <summary>
		/// Get the engr_unit_id associated with a given (unique) abbreviation.
		/// </summary>
		/// <param name="abbreviation">The unique abbreviation [abbrev]</param>
		/// <returns>The integer value of the [engr_unit_id] associated with the given abbreviation.
		/// Returns -1 if the abbreviation does not exist in the database.</returns>
		public int GetEngrUnitIdFromAbbreviation(string abbreviation)
		{
			OpenConnection();

			try
			{
				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.GetEngrUnitIdFromAbbrev", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@Abbrev", abbreviation));

					// execute the command
					object FK = null;
					using (SqlDataReader rdr = cmd.ExecuteReader())
					{
						while (rdr.Read())
						{
							FK = rdr["engr_unit_id"];
						}
					}

					_connection.Close();

					//return FK == null ? -1 : (int)FK;
                    if (FK == null)
                    {
                        _errorLog.writeToLog(_currentDB,
                            String.Format("Unable to grab ENGR unit from abbr:{0}",abbreviation));
                        return -1;
                    }
                    else 
                    {
                        return (int)FK;
                    }
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				// Return -1 if the stage was not inserted
				//Console.WriteLine("Standardized_Wrapper.cs\\GetEngrUnitIdFromAbbreviation" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}
		}

		/// <summary>
		/// Insert a new Waveform entry into the Standardized Database
		/// </summary>
		/// <param name="sensorId">Sensor Id (Foreign key)</param>
		/// <param name="gmt">Time of Sampling start</param>
		/// <param name="rpm">Machine RPM at Sampling start</param>
		/// <param name="sampleRate">Sample rate (samples per second)</param>
		/// <param name="bitsPerSample">Bits used for each sample (Length of SampleData = Bits per Sample * Number of Samples)</param>
		/// <param name="sampleData">The samples</param>
		/// <param name="engrUnitId">Engineering unit Id (Foreign key)</param>
		/// <param name="status">Status</param>
		/// <returns>True if the row was successfully added; False otherwise</returns>
		public bool InsertWaveform(int sensorId, DateTime gmt, Single? rpm, int sampleRate, int bitsPerSample, Byte[] sampleData, int engrUnitId, Byte[] status)
		{
			// TODO: implement exception classes to better handle failed insertions?

			try
			{
				OpenConnection();

				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.InsertWaveform", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@SensorId", sensorId));
					cmd.Parameters.Add(new SqlParameter("@GMT", gmt));
					cmd.Parameters.Add(new SqlParameter("@RPM", rpm));
					cmd.Parameters.Add(new SqlParameter("@SampleRate", sampleRate));
					cmd.Parameters.Add(new SqlParameter("@BitsPerSample", bitsPerSample));
					cmd.Parameters.Add(new SqlParameter("@SampleData", sampleData));
					cmd.Parameters.Add(new SqlParameter("@EngrUnitId", engrUnitId));
					cmd.Parameters.Add(new SqlParameter("@Status", status));

					// execute the command
					int rowsAffected = cmd.ExecuteNonQuery();
					_connection.Close();

					//return rowsAffected == 1 ? true : false;
                    if (rowsAffected == 1)
                    {
                        return true;
                    }
                    else 
                    {
                        _errorLog.writeToLog(_currentDB,
                            String.Format("Unable to insert waveform, sensorId:{0} Time:{1}",sensorId,gmt));
                        return false;
                    }
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				// Return false if the waveform was not inserted
				//Console.WriteLine("Standardized_Wrapper.cs\\InsertWaveform" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return false;
			}
		}

		/// <summary>
		/// Returns true if the machine condition was successfully added, or already existed.
		/// </summary>
		/// <param name="machineId"></param>
		/// <param name="startDate"></param>
		/// <param name="endDate"></param>
		/// <param name="condition"></param>
		/// <param name="dataSource">"ADRE", "ADAPT", or "System1"</param>
		/// <returns>Returns true if the machine condition was successfully added, or already existed; False otherwise.</returns>
		public bool InsertMachineCondition(int machineId, DateTime startDate, DateTime endDate, string condition, string comments, string dataSource)
		{
			// Get [data_source_id] from the name
			int dataSourceId = GetDataSourceIdByName(dataSource);

            if (dataSourceId == -1)
            {
                _errorLog.writeToLog(_currentDB,
                    String.Format("Unable to insert machine Cndition, machineId:{0} Time:{1}", machineId, startDate));
                return false;
            }

			// Try insert condition
			try
			{
				OpenConnection();

				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.InsertMachineCondition", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@MachineId", machineId));
					cmd.Parameters.Add(new SqlParameter("@StartDate", startDate));
					cmd.Parameters.Add(new SqlParameter("@EndDate", endDate));
					cmd.Parameters.Add(new SqlParameter("@Condition", condition));
					cmd.Parameters.Add(new SqlParameter("@Comments", comments));
					cmd.Parameters.Add(new SqlParameter("@DataSourceId", dataSourceId));

					// execute the command
					cmd.ExecuteNonQuery();
					_connection.Close();
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				// Return false if the condition was not inserted
				//Console.WriteLine("Standardized_Wrapper.cs\\InsertMachineCondition" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return false;
			}
			return true;
		}

		public bool InsertMachineCondition(int machineId, DateTime startDate, DateTime endDate, string condition, string comments, int dataSourceId)
		{
			// Get [data_source_id] from the name
            if (dataSourceId == -1)
            {
                _errorLog.writeToLog(_currentDB,
                    String.Format("Unable to insert machine Cndition, machineId:{0} Time:{1}", machineId, startDate));
                return false;
            }

			// Try insert condition
			try
			{
				OpenConnection();

				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.InsertMachineCondition", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@MachineId", machineId));
					cmd.Parameters.Add(new SqlParameter("@StartDate", startDate));
					cmd.Parameters.Add(new SqlParameter("@EndDate", endDate));
					cmd.Parameters.Add(new SqlParameter("@Condition", condition));
					cmd.Parameters.Add(new SqlParameter("@Comments", comments));
					cmd.Parameters.Add(new SqlParameter("@DataSourceId", dataSourceId));

					// execute the command
					cmd.ExecuteNonQuery();
					_connection.Close();
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				// Return false if the condition was not inserted
				//Console.WriteLine("Standardized_Wrapper.cs\\InsertMachineCondition" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return false;
			}
			return true;
		}
		#endregion


		#region Private Wrapper Functions

		private int GetCountOfMachines()
		{
			try
			{
				using (SqlCommand sqlCmnd = new SqlCommand())
				{
					sqlCmnd.CommandType = System.Data.CommandType.Text;
					sqlCmnd.Connection = _connection;

					sqlCmnd.CommandText = String.Format(
						"SELECT Count(*) FROM [{0}].[dbo].[machine];"
						, _databaseName);

					OpenConnection();
					using (SqlDataReader rdr = sqlCmnd.ExecuteReader())
					{
						while (rdr.Read())
						{
							return (int)rdr[0];
						}
					}
					sqlCmnd.Connection.Close();
				}
			}
			catch (SqlException sqlEx)
			{
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}
			return 0;
		}

		/// <summary>
		/// Get the machine_id of the newest/latest machine that has been added
		/// </summary>
		/// <returns>The integer value of the [machine_id]; -1 otherwise</returns>
		private int GetLatestMachineId()
		{
			OpenConnection();

			try
			{
				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.GetLatestMachineId", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;

					// execute the command
					object PK = null;
					using (SqlDataReader rdr = cmd.ExecuteReader())
					{
						while (rdr.Read())
						{
							PK = rdr["machine_id"];
						}
					}

					_connection.Close();

					return PK == null ? -1 : (int)PK;
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				//Console.WriteLine("Standardized_Wrapper.cs\\GetLatestMachineId Error: " + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}
		}
        
		/// <summary>
		/// Get the [machine_id] associated with a given serial number
		/// </summary>
		/// <param name="serialNumber">Serial number</param>
		/// <returns>The integer value of the [machine_id] with the given serial number; -1 otherwise</returns>
		private int GetMachineIdBySerial(string serialNumber)
        {

			OpenConnection();

			try
			{

				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.GetMachineIdBySerial", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@Serial", serialNumber));

					// execute the command
					object PK = null;
					using (SqlDataReader rdr = cmd.ExecuteReader())
					{
						while (rdr.Read())
						{
							PK = rdr["machine_id"];
						}
					}

					_connection.Close();

					return PK == null ? -1 : (int)PK;
				}

			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				//Console.WriteLine("Standardized_Wrapper.cs\\GetMachineIdBySerial Error: " + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="machineId"></param>
		/// <param name="gearToothCount"></param>
		/// <param name="pinionToothCount"></param>
		/// <param name="sunToothCount"></param>
		/// <param name="planetToothCount"></param>
		/// <param name="ringToothCount"></param>
		/// <param name="planetCount"></param>
		/// <returns></returns>
		private int GetStageIdByProperties(int machineId, Fixed? fixedGear, int? gearToothCount, int? pinionToothCount, int? sunToothCount, int? planetToothCount, int? ringToothCount, int? planetCount)
		{
			OpenConnection();

			try
			{
				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.GetStageIdByMachineIdAndProperties", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@MachineId", machineId));
					cmd.Parameters.Add(new SqlParameter("@GearToothCount", gearToothCount));
					cmd.Parameters.Add(new SqlParameter("@PinionToothCount", pinionToothCount));
					cmd.Parameters.Add(new SqlParameter("@SunToothCount", sunToothCount));
					cmd.Parameters.Add(new SqlParameter("@PlanetToothCount", planetToothCount));
					cmd.Parameters.Add(new SqlParameter("@RingToothCount", ringToothCount));
					cmd.Parameters.Add(new SqlParameter("@PlanetCount", planetCount));
					if (fixedGear == null)
						cmd.Parameters.Add(new SqlParameter("@Fixed", null));
					else
						cmd.Parameters.Add(new SqlParameter("@Fixed", (int)fixedGear));

					// execute the command
					object PK = null;
					int rowCount = 0;
					using (SqlDataReader rdr = cmd.ExecuteReader())
					{
						while (rdr.Read())
						{
							PK = rdr["stage_id"];
							rowCount++;
						}
					}

					_connection.Close();

					if (rowCount != 1) return -1;
					return (int)PK;
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				//Console.WriteLine("Standardized_Wrapper.cs\\GetStageIdByProperties Error: " + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		private int GetLatestStageId()
		{
			OpenConnection();

			try
			{
				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.GetLatestStageId", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;

					// execute the command
					object PK = null;
					using (SqlDataReader rdr = cmd.ExecuteReader())
					{
						while (rdr.Read())
						{
							PK = rdr["stage_id"];
						}
					}

					_connection.Close();

					return PK == null ? -1 : (int)PK;
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				//Console.WriteLine("Standardized_Wrapper.cs\\GetLatestStageId" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="pointName"></param>
		/// <param name="machineId"></param>
		/// <returns></returns>
		private int GetSensorIdByNameAndStage(string pointName, int stageId)
		{
			OpenConnection();

			try
			{
				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.GetSensorIdByNameAndStage", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@PointName", pointName));
					cmd.Parameters.Add(new SqlParameter("@StageId", stageId));

					// execute the command
					object PK = null;
					int rowCount = 0;
					using (SqlDataReader rdr = cmd.ExecuteReader())
					{
						while (rdr.Read())
						{
							PK = rdr["sensor_id"];
							rowCount++;
						}
					}

					_connection.Close();

					if (rowCount != 1) return -1;
					return (int)PK;
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				//Console.WriteLine("Standardized_Wrapper.cs\\GetSensorIdByNameAndMachine" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		private int GetLastestSensorId()
		{
			OpenConnection();

			try
			{
				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.GetLatestSensorId", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;

					// execute the command
					object PK = null;
					using (SqlDataReader rdr = cmd.ExecuteReader())
					{
						while (rdr.Read())
						{
							PK = rdr["sensor_id"];
						}
					}

					_connection.Close();

					return PK == null ? -1 : (int)PK;
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				//Console.WriteLine("Standardized_Wrapper.cs\\GetLatestSensorId" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="dataSourceName"></param>
		/// <returns></returns>
		private int GetDataSourceIdByName(string dataSourceName)
		{
			OpenConnection();

			try
			{
				using (SqlCommand cmd = new SqlCommand(_databaseName + ".dbo.GetDataSourceIdByName", _connection))
				{
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@Name", dataSourceName));

					// execute the command
					object PK = null;
					int rowCount = 0;
					using (SqlDataReader rdr = cmd.ExecuteReader())
					{
						while (rdr.Read())
						{
							PK = rdr["data_source_id"];
							rowCount++;
						}
					}

					_connection.Close();

					if (rowCount != 1) return -1;
					return (int)PK;
				}
			}
			catch (SqlException sqlEx)
			{
				_connection.Close();
				//Console.WriteLine("Standardized_Wrapper.cs\\GetDataSourceIdByName" + sqlEx.Message);
                _errorLog.writeToLog(_currentDB, sqlEx.Message);
				return -1;
			}
		}
		#endregion
	}
}
